package com.mxnavi5.example.DataStream;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.typeinfo.TypeHint;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.RestOptions;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;


public class MyWordCount {

    public static void main(String[] args) throws Exception {
        Configuration configuration = new Configuration();
        configuration.setInteger(RestOptions.PORT,8081);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(configuration);
        env.setParallelism(1);
        DataStreamSource<String> sourceStream =
                env.readTextFile("E:\\workspace\\flink-example\\src\\main\\resources\\hello.txt");
        sourceStream.print("gggg");
        SingleOutputStreamOperator<String> stringSingleOutputStreamOperator = sourceStream.flatMap(new FlatMapFunction<String, String>() {
            @Override
            public void flatMap(String s, Collector<String> collector) throws Exception {
                String[] arr = s.split(" ");
                for (String s1 : arr) {
                    collector.collect(s1);
                }
            }
        });
        SingleOutputStreamOperator<Tuple2<String, Integer>> mapStream
                = stringSingleOutputStreamOperator.map(word -> Tuple2.of(word, 1))
                .returns(TypeInformation.of(new TypeHint<Tuple2<String,Integer>>(){}));
        mapStream.keyBy(t->t.f0).sum(1).print("111");
        mapStream.keyBy(0).sum(1).print("222");
        mapStream.keyBy(0).reduce(new ReduceFunction<Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> reduce(Tuple2<String, Integer> t1, Tuple2<String, Integer> t2) throws Exception {
                return Tuple2.of(t1.f0, t1.f1+t2.f1);
            }
        }).print("333");

        env.execute();

    }
}
